package manager

import (
	"github.com/tianjigames/fairy/model"
	"github.com/tianjigames/fairy/util"
	"math"
	"sync"
	"time"
)

var (
	TimeManager *timeManager
	timeOnce sync.Once
)

const MaxTimeBase = math.MaxInt64

type timeManager struct {
	BaseManager
	TimeBase int64 //踢人的时间间隔累计值
	Times int64 //踢人的时间间隔累计值 超过MaxTimeBase的次数
	LastTimeForSecond int //上一次踢人的秒数
	LastTimeForMinute int //上一次踢人的分钟
	LastTimeForHour int //上一次踢人的小时
	LastTimeForDay int //上一次踢人的天
	LastTimeForYear int //上一次踢人的年
	LastTimeForDayOfMonth int //上一次踢人的天在一年中的天数
	LastTimeForMonth int //上一次踢人的月份

	MTimeForSencond int    //当前秒数
	MTimeForMinute int     //当前分钟
	MTimeForHour int       //当前小时
	MTimeForDay int        //当前在的天
	MTimeForYear int       //当前的年
	MTimeForDayOfMonth int //当前在一个月中的天数
	MTimeForMonth int      //当前的月份
	Timer *model.NowTimer  //定时器对象  定时踢人
}

func NewTimeManager() *timeManager {
	timeOnce.Do(func() {
		TimeManager = &timeManager{
			Timer: &model.NowTimer{},
		}
	})
	return TimeManager
}

func (p *timeManager) Init()  {
	p.TimeBase = 0
	p.Times = 0
	now := time.Now()
	p.MTimeForSencond = now.Second()
	p.MTimeForMinute = now.Minute()
	p.MTimeForHour = now.Hour()
	p.MTimeForDay = now.YearDay()
	p.MTimeForDayOfMonth = now.Day()
	p.MTimeForMonth = util.NowMonth(now)
	p.MTimeForYear = now.Year()
}

/**
改变基本时间 增加值为上一次踢人的时间到现在的差值
 */
func (p *timeManager) changeTimeBase(addTime int64)  {
	if p.TimeBase + addTime >= MaxTimeBase {
		p.Times = (p.TimeBase + addTime) / MaxTimeBase
		p.TimeBase = (p.TimeBase + addTime) % MaxTimeBase
	}else {
		p.TimeBase += addTime
	}
}

/**
踢下线
 */
func (p *timeManager) Tick(now,delayTime int64)  {
	//增加基本时间:增加值为上一次踢人的时间到现在的时间差
	p.changeTimeBase(delayTime)
	if !p.Timer.IsSetTimer() {//如果还没有设置定时时间 1秒之后启动定时器
		p.Timer.BeginTimer(1000,now)
	}

	if p.Timer.CountingTimer(now) {//定时周期时间到 重置上一次踢人的时间
		p.LastTimeForSecond = p.MTimeForSencond
		p.LastTimeForMinute = p.MTimeForMinute
		p.LastTimeForHour = p.MTimeForHour
		p.LastTimeForDay = p.MTimeForDay
		p.LastTimeForDayOfMonth = p.MTimeForDayOfMonth
		p.LastTimeForMonth = p.MTimeForMonth
		p.LastTimeForYear = p.MTimeForYear

		now := time.Now()
		p.MTimeForSencond = now.Second()
		p.MTimeForMinute = now.Minute()
		p.MTimeForHour = now.Hour()
		p.MTimeForDay = now.YearDay()
		p.MTimeForDayOfMonth = now.Day()
		p.MTimeForMonth = util.NowMonth(now)
		p.MTimeForYear = now.Year()
	}
}





























